import PyQt5.sip
import PyQt5
from PyQt5.QtWidgets import QStyle
from PyQt5.QtWidgets import QAbstractItemView, QMainWindow, QApplication, QMessageBox, QCheckBox, QHBoxLayout
from PyQt5.QtWidgets import QFileDialog
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtCore import QAbstractTableModel, QModelIndex
from PyQt5.QtCore import QDateTime, QTime, Qt
import os
import sys
import csv
import config_json
import getpath
import json
import subprocess
import bjItems
import spectro
# import icp
import csonh
import weight
import diding
import guangdu
from objectview import ObjectView, ObjectModel
from FlowLayout import FlowLayout 
import logging
import traceback
from delegates import NotEditDelegate,FloatEditDelegateQt,EditDelegateQt,DateTimeEditDelegateQt,DoubleViewDelegate,ComboBoxDelegateQt,DateTimeEditDelegateQt
import myglobal
# import icpms
import zwk
from ImageView import ImageView
import time
import datetime
from MyWidget import MyWidget
# import watch
# from BiaoYe import BiaoYe
import mystyle
import dblims
# import pyodbc
import pymssql
import ui_mainw
def datetime_str(d2):
    return "%04d-%02d-%02d %02d:%02d:%02d" % (d2.year,d2.month,d2.day,d2.hour,d2.minute,d2.second)

def inList(one, l):
    for i in range(len(l)):
        if one == l[i]:
            return i
    return -1

def timestr():
    db = QDateTime.currentDateTime()
    db_str = db.toString("yyyy_MM_dd_hh_mm_ss")
    return db_str

class MainW(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        myglobal.mainw=self
        self.xlswidget=None
        self.ui = ui_mainw.Ui_MainWindow()
        self.ui.setupUi(self)
        config_json.read_setting()
        try:
            myglobal.server=dblims.Server()
            self.versions=myglobal.server.getversion()
            # if config_json.setting["version"] in self.versions:
            #     pass
            # else:
            #     QtWidgets.QMessageBox.information(None, "", "版本不对！")
            #         # self.ui.centralwidget.setVisible(False)
        except pymssql.exceptions.OperationalError as e:
            QMessageBox.information(None,"",str(e))
        n=datetime.datetime.now().year % 2000
        n0=n-1
        n=str(n)
        n0=str(n0)
        self.sample_name_pattern="(%s|%s)[A-Z][A-Z][0-9]*-[1-9]" % (n,n0)
        self.chks=[]
        self.appends=[]
        self.db=None
    
        self.ui.spinBox_day.setValue(1)
        self.ui.spinBox_day.valueChanged.connect(self.day_change)

        if config_json.setting["sblx"] not in config_json.setting["sblx_list"]:
            config_json.setting["sblx"]=config_json.setting["sblx_list"][0]

        self.setWindowTitle("数据上报_"+config_json.setting["sblx"])
        self.h = FlowLayout(self.ui.groupBox)
        self.h2_append = QtWidgets.QHBoxLayout(self.ui.groupBox_append)
        self.h2_append.setContentsMargins(1, 1, 1, 1)
        self.h2_append.setSpacing(1)
        self.h3_biaoye = QtWidgets.QHBoxLayout(self.ui.widget_biaoye)

        self.h3_biaoye.setContentsMargins(0, 0, 0, 0)
        self.h3_biaoye.setSpacing(0)

        self.objects = []  # self.db.getDataDays(200)
        self.model = ObjectModel()
        self.ui_tableView =self.ui.tableView
        # ObjectView(self.model)
        # vbox = QtWidgets.QVBoxLayout(self.ui.groupBox_2)
        # vbox.addWidget(self.ui_tableView)

        self.ui.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.ui.btnSelect.clicked.connect(self.select)
        self.ui.btnUnselect.clicked.connect(self.unselect)
        self.ui.btnSelect.setText("↓")
        self.ui.btnUnselect.setText("↑")
        self.ui.btnClear.clicked.connect(self.clear)
        self.ui.btnLims.clicked.connect(self.lims)
        # self.ids = []
        self.objects2=[]
        self.model2 = ObjectModel()
        # self.ui.tableView_report = self.ui.tableView_report
        # ObjectView(self.model2)
        # vbox = QtWidgets.QVBoxLayout(self.ui.groupBox_3)
        # vbox.addWidget(self.ui.tableView_report)
        # self.ui.actionsyy.setVisible(False)
        self.ui.actionsetting.triggered.connect(self.setting)
        self.ui.actionffbh.triggered.connect(self.set_ffbh)
        self.ui.action_exit.triggered.connect(self.exit_app)
        self.ui.actionsave_as.triggered.connect(self.save_as)
        self.ui.actionsyy.triggered.connect(self.set_syy)
        self.ui.action_paste.triggered.connect(self.paste)
        # self.ui.tableView_report.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.ui.tableView_report.setSortingEnabled(True)
        self.ui.tableView_report.horizontalHeader(
        ).setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.tableView_report.horizontalHeader(
        ).customContextMenuRequested.connect(self.showCloumnMenu)

        yqbh = config_json.setting["yqbh"]
        # syy = myglobal.server.getsyy()#config_json.setting["syy"]
        # for i in syy:
        #     self.ui.cmb_syy.addItem(i)
        #     self.ui.cmb_syyqm.addItem(i)
        #     self.ui.cmb_ysry.addItem(i)
        # self.refresh_syy()
        # self.ui.lineEdit_yqbh.setText(yqbh)
        self.ui.cmb_ffbh.setText(config_json.setting["current"]["ffbh"])
        self.ui.cmb_ff2.setText(config_json.setting["current"]["ff2"])
        self.ui.cmb_js2.setText(config_json.setting["current"]["js2"])
        self.ui.cmb_syy.setText(config_json.setting["current"]["syy"])
        self.ui.cmb_syyqm.setText(config_json.setting["current"]["syyqm"])
        self.ui.cmb_ysry.setText(config_json.setting["current"]["ysry"])
        
        # self.ui.cmb_ffbh.setText(config_json.setting["current"]["ffbh"])
        # self.ui.cmb_syy.setCurrentIndex(config_json.setting["current"]["syy"])
        # self.ui.cmb_ysry.setCurrentIndex(
        #     config_json.setting["current"]["ysry"])
        # self.ui.cmb_syyqm.setCurrentIndex(
        #     config_json.setting["current"]["syyqm"])
        # self.ui.cmb_syy.currentIndexChanged[int].connect(self.syy_change)
        # self.ui.cmb_ysry.currentIndexChanged[int].connect(self.ysry_change)
        # # self.ui.cmb_ffbh.currentIndexChanged[int].connect(self.ffbh_change)
        # self.ui.cmb_syyqm.currentIndexChanged[int].connect(self.syyqm_change)
        self.ui.pushButton_query.clicked.connect(self.import_last)   
        self.ui.action.triggered.connect(self.beizhu)
        self.ui.action_version.triggered.connect(self.version)
        self.ui.action_upgrade.triggered.connect(self.upgrade)
        self.ui.action_sync.setVisible(False)# triggered.connect(self.sync)
        # self.ui.groupBox_2.setTitle("")
        # self.ui.groupBox_3.setTitle("")
        #__init__
        if config_json.setting["sblx"] in ["weight","diding","guangdu"]:
            self.ui.widget_up.setVisible(False)
            self.ui.pushButton_add.setVisible(True)
            self.ui.pushButton_del.setVisible(True)
            self.ui.pushButton_calc.setVisible(True)
        else:
            self.ui.widget_up.setVisible(True)
            self.ui.pushButton_calc.setVisible(False)
            self.ui.pushButton_add.setVisible(False)
            self.ui.pushButton_del.setVisible(False)
        #__init__
        if config_json.setting["sblx"] in ["ncs_cs_db","ncs_onh_db"]:
            self.ui.spinBox_day.setVisible(True)
            self.ui.label_7.setVisible(True)
        else:
            self.ui.spinBox_day.setVisible(False)
            self.ui.label_7.setVisible(False)
        #__init__
        self.ui.pushButton_add.clicked.connect(self.addOne)
        self.ui.pushButton_calc.clicked.connect(self.calc)
        self.ui.pushButton_ffbh.clicked.connect(self.select_method)
        self.ui.tableView_report.dragbottom.connect(self.dragbottom_trig)
        self.ui.pushButton_del.clicked.connect(self.delOne)
        self.ui.pushButton_import.clicked.connect(self.import_click)
        self.ui.pushButton_selectAll.clicked.connect(self.selectall)
        self.ui.statusbar.setVisible(False)
        # self.t1=QtWidgets.QPushButton("930")
        # self.t1.clicked.connect(self.t1_click)
        # self.t2=QtWidgets.QPushButton("ncsdb")
        # self.t2.clicked.connect(self.t2_click)
        # self.h.addWidget(self.t1)
        # self.h.addWidget(self.t2)
        self.dblViewDele = DoubleViewDelegate("%.07f")
        
        self.dateDelegate=DateTimeEditDelegateQt()#
        self.editDelegate=EditDelegateQt()
        self.floatEdit=FloatEditDelegateQt()
        self.comboDelegate=ComboBoxDelegateQt(["圆管","棒材","板材","剖管","扁钢丝"])
        self.notedit=NotEditDelegate()
        
        self.set_database()
        self.ui.actionffbh.setVisible(False)
        self.ui.action.setVisible(False)
        # self.ui.groupBox_append.setTitle("")
        # l1=QtWidgets.QLabel("nb:")
        # l2=QtWidgets.QLabel("Sc")
        # v1=QtWidgets.QVBoxLayout()
        # v1.addWidget(l1)
        # v1.addWidget(l2)
        # self.h.addLayout(v1)
        if config_json.setting["watch_path"]:
            if sys.version_info.minor>4:#>3.4
                from watch import Watch
                self.w=Watch(config_json.setting["watch_path"])
                self.w.created.connect(self.watch_file)
        self.ui.comboBox_files.activated.connect(self.file_selected) 
        if config_json.setting["dark"]==1:
            mystyle.darkStyle(True)
        elif config_json.setting["dark"]==0:
            mystyle.darkStyle(False)        
        else:
            pass
        self.action_style_dark = QtWidgets.QAction(self)
        self.action_style_dark.setText("暗色")
        self.action_style_dark.triggered.connect(self.style_dark)
        self.ui.menu.addAction(self.action_style_dark)
        self.action_style_light = QtWidgets.QAction(self)
        self.action_style_light.setText("亮色")
        self.action_style_light.triggered.connect(self.style_light)
        self.ui.menu.addAction(self.action_style_light)
        self.action_style_normal = QtWidgets.QAction(self)
        self.action_style_normal.setText("正常")
        self.action_style_normal.triggered.connect(self.style_normal)
        self.ui.menu.addAction(self.action_style_normal)
        self.action_upgrade_notcheck = QtWidgets.QAction(self)
        self.action_upgrade_notcheck.setText("升级")
        self.action_upgrade_notcheck.triggered.connect(self.upgrade_notcheck)
        self.ui.menu.addAction(self.action_upgrade_notcheck)
        self.export_num=0
        self.pushButton_syy=self.addButton(self.ui.cmb_syy)
        self.pushButton_syyqm=self.addButton(self.ui.cmb_syyqm)
        self.pushButton_ysry=self.addButton(self.ui.cmb_ysry)

        self.pushButton_syy.clicked.connect(self.select_syy)
        self.pushButton_syyqm.clicked.connect(self.select_syy)
        self.pushButton_ysry.clicked.connect(self.select_syy)
    def addButton(self,lineEdit):
        btn = QtWidgets.QPushButton("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/image/images/th.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        btn.setIcon(icon1)
        btn.setStyleSheet("""QPushButton {
                               border: 0px solid #32CD32;
                             }""")
        btn.setCursor(Qt.PointingHandCursor);
        widgetAction = QtWidgets.QWidgetAction(self);
        widgetAction.setDefaultWidget(btn);
        lineEdit.addAction(widgetAction,QtWidgets.QLineEdit.TrailingPosition);
        return btn
    def btn_click(self):
        print("click")
    def select_syy(self,e):
        # logging.info([dir(e),self.sender()])
        sender=0
        # if self.sender()== self.ui.pushButton_syy:
        #     sender=0
        # elif self.sender()== self.ui.cmb_syyqm:
        #     sender=1
        # elif self.sender()== self.ui.cmb_ysry:
        #     sender=2
        from dlgsyy import DlgSyy
        d = DlgSyy()
        d.setWindowTitle("人员")
        d.show()
        r = d.exec_()
        if r == 1:
            one=d.select_row
            logging.info(one)
            # self.ui.cmb_ffbh.clear()
            # self.ui.cmb_ff2.clear()
            # self.ui.cmb_js2.clear()
            if self.sender()==self.pushButton_syy:
                self.ui.cmb_syy.setText(one[0])
                self.ui.cmb_syyqm.setText(one[0])
            elif self.sender()==self.pushButton_syyqm:
                self.ui.cmb_syyqm.setText(one[0])
            elif self.sender()==self.pushButton_ysry:
                self.ui.cmb_ysry.setText(one[0])
        else:
            pass        
    # def refresh_syy(self):
    #     ff = myglobal.server.getsyy()#config_json.setting["syy"]
    #     self.completer = PyQt5.QtWidgets.QCompleter(ff, self)
    #     self.completer.setFilterMode(Qt.MatchContains)
    #     self.completer.setCaseSensitivity(Qt.CaseInsensitive)
    #     self.completer.setCompletionMode(
    #         PyQt5.QtWidgets.QCompleter.UnfilteredPopupCompletion)
    #     self.ui.cmb_syy.clear()
    #     self.ui.cmb_syy.addItems(ff)
    #     # self.ui.cmb_syy.setCurrentIndex(0)
    #     self.ui.cmb_syy.setEditable(True)
    #     self.ui.cmb_syy.setCompleter(self.completer)
    #     self.ui.cmb_syyqm.clear()
    #     self.ui.cmb_syyqm.addItems(ff)
    #     # self.ui.cmb_syyqm.setCurrentIndex(
    #     #     config_json.setting["current"]["ffbh"])
    #     self.ui.cmb_syyqm.setEditable(True)
    #     self.ui.cmb_syyqm.setCompleter(self.completer)
    #     self.ui.cmb_ysry.clear()
    #     self.ui.cmb_ysry.addItems(ff)
    #     # self.ui.cmb_ysry.setCurrentIndex(
    #     #     config_json.setting["current"]["ffbh"])
    #     self.ui.cmb_ysry.setEditable(True)
    #     self.ui.cmb_ysry.setCompleter(self.completer)

    def file_selected(self,at):
        logging.info(at)
        fname=self.ui.comboBox_files.itemText(at)
        config_json.setting["database"] = fname
        self.import_file(fname)
        self.ui.comboBox_files.removeItem(at)
    def watch_file(self,fname):
        self.ui.comboBox_files.addItem(fname)
        logging.info(fname)
    def paste(self):
        clipboard = QtWidgets.QApplication.clipboard()
        t = clipboard.text()
        logging.info(t)
        if t != "":
            # ,"uni_cs","uni_on"]:
            if config_json.setting["sblx"] in ["weight","guangdu","diding"]:
                objs=self.db.import_text_bytitle(t)  # clip board from excel
                print(self.objects)
                for one in objs:
                    self.objects2.append(one)
                print(self.objects2)
                self.refresh_grid2()
    def finish_capture(self,data):
        self.showNormal()
        self.iv.addImage(data)
    def screenShot(self):
        self.showMinimized()
        time.sleep(0.2)
        self.screenShotWg.start()        
    def clear_layout(self, layout):
        while True:
            child = layout.takeAt(0)
            if child is None:
                break
            else:
                child.widget().deleteLater()
    def import_click(self):
        if config_json.setting['sblx'] in ["ncs_cs_db","ncs_onh_db"]:
            self.import_last()
            return
        FileDialog = QFileDialog(self)
        if config_json.setting["database"]!=None:
            folder = os.path.split(config_json.setting["database"])[0]
            if os.path.exists(folder):
                pass
            else:
                folder=os.path.join(os.path.expanduser('~'), "Desktop")
        else:
            folder=os.path.join(os.path.expanduser('~'), "Desktop")
        if config_json.setting["sblx"] in ["930"]:
            fil = "csv Files (*.csv);;All Files (*)"
        elif config_json.setting["sblx"] == "spec":
            fil = "xlsx Files (*.xlsx);;All Files (*)"
        elif config_json.setting["sblx"] in  ["6300","zwk"]:
            fil = "xls Files (*.xls);;All Files (*)"            
        elif config_json.setting["sblx"] == "ajl_pdf":
            fil = "pdf Files (*.pdf);;All Files (*)"
        elif config_json.setting["sblx"] == "icap":
            fil = "Html Files (*.html);;All Files (*)"
        elif config_json.setting["sblx"] in ["ajl8900"]:
            fil = "xlsx Files (*.xlsx);;All Files (*)"    
        elif config_json.setting["sblx"] in ["icap_q"]:
            fil = "xml Files (*.xml);;All Files (*)"                
        else:
            fil = "All Files (*)"
        FileDirectory = FileDialog.getOpenFileName(
            self, 'select import file', folder, fil)  # 选择目录，返回选中的路径
        # logging.info(FileDirectory)
        fname = FileDirectory[0]
        if fname == "":
            pass
        else:
            try:
                config_json.setting["database"] = fname
                self.import_file(fname)
            except:
                traceback.print_exc() 

    def import_last(self):
        logging.info("last")
        try:
            self.import_file(config_json.setting["database"])
        except:
            traceback.print_exc()                
    def import_file(self, fname):
        self.export_num=0
        logging.info(fname)
        if config_json.setting["sblx"] in ["icap","icap_q"]:
            self.ui.lineEdit_filename.setText(os.path.split(os.path.split(fname)[0])[1])
        elif config_json.setting["sblx"] in ["ncs_cs_db","ncs_onh_db"]:
            pass
        else:
            self.ui.lineEdit_filename.setText(os.path.splitext(os.path.basename(fname))[0])
        self.clearResult()
        self.query()
    def delOne(self):
        selections = self.ui.tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        objs=[]
        for i in range(len(list1)):
            current = list1[i]
            obj = self.objects2[current.row()]
            if obj in objs:
                pass
            else:
                objs.append(obj)
        for obj in objs:
            self.objects2.remove(obj)
        self.refresh_grid2() 
    def clearResult(self):
        pass
        # self.clear()                
    def dragbottom_trig(self,indexs):
        print(indexs)  
        first=indexs[0]
        col=first.column()
        row=first.row()
        print(dir(first))
        obj=self.objects2[row]
        v=getattr(obj,self.db.properties[col]["attr"])
        if self.db.properties[col]["delegate"]!=None:
            # v=getattr(firstobj,self.db.properties[col]["attr"])
            for one in indexs[1:]:
                # print(one.row())
                obj=self.objects2[one.row()]
                setattr(obj,self.db.properties[col]["attr"],v)
            self.refresh_grid2()        
    def select_method(self):
        from dlgffbh import DlgFfbh
        d = DlgFfbh()
        d.setWindowTitle("方法")
        d.show()
        r = d.exec_()
        if r == 1:
            one=d.select_row

            logging.info(one)
            # self.ui.cmb_ffbh.clear()
            # self.ui.cmb_ff2.clear()
            # self.ui.cmb_js2.clear()
            self.ui.cmb_ffbh.setText(one[0])
            self.ui.cmb_ff2.setText(one[2])
            self.ui.cmb_js2.setText(one[3])
            # self.ui.cmb_ffbh.setCurrentIndex(self.ui.cmb_ff2.count()-1)
            # self.ui.cmb_ff2.setCurrentIndex(self.ui.cmb_ff2.count()-1)
            # self.ui.cmb_js2.setCurrentIndex(self.ui.cmb_js2.count()-1)
        else:
            pass
    def addOne(self):
        new=self.db.addOne()
        self.objects2.append(new)
        # self.model2.appendObjects([new])
        # logging.info(self.objects2)
        logging.info(self.model2.objects)
        logging.info(self.model2.properties)
        self.ui.tableView_report.setFocus()
        self.refresh_grid2()  
    def calc(self):
        self.db.calc()
        self.refresh_grid()      
    def showCloumnMenu(self, pos):
        logging.info("showCloumnMenu")
        logging.info(pos)
        try:
            self.db.showColumnMenu(pos)
        except AttributeError:
            pass

    def contextMenuEvent(self, event):
        # try:
        # logging.info(dir(self.db))
        self.db.contextMenuEvent(event)
        # except AttributeError:
        #     logging.info("AttributeError")
        #     pass
    def firstChannel(self):
        try:
            groups = {}
            for i in range(len(self.db.properties)):
                f = self.db.properties[i]
                if f.get("ele") is None:
                    pass
                else:
                    element = f["ele"][0]
                    if groups.get(element) is None:
                        groups[element] = []
                    groups[element].append(f)
            for one in groups.keys():
                # logging.info(groups[one])
                for i in range(len(groups[one])):  # wave in groups[one]:
                    if i == 0:
                        if groups[one][i].get("hide",False)==True:#"Final" in groups[one][i]['ele'][0] or "CPS" in groups[one][i]['ele'][0] or "内标" in groups[one][i]['ele'][0]:
                            pass
                        else:
                            groups[one][i]["visible"] = True
                    else:
                        groups[one][i]["visible"] = False
            for i in range(len(self.db.properties)):
                if self.db.properties[i].get("ele") is None:
                    pass
                else:
                    self.columnVisible(i, self.db.properties[i]["visible"])

        except ValueError as e:
            pass            
    def columnVisible(self, i, visible):
        self.db.properties[i]["visible"]= visible
        if visible:
            self.chks[i].setChecked(True)
            self.ui.tableView_report.showColumn(i)
            self.ui.tableView.showColumn(i)
        else:
            self.chks[i].setChecked(False)
            self.ui.tableView_report.hideColumn(i)
            self.ui.tableView.hideColumn(i)            
    def validChannel(self):
        for record in self.objects:
            for i in range(len(self.db.properties)):
                one = self.db.properties[i]
                if one.get("ele") is None:
                    pass
                else:
                    v=getattr(record,one["attr"])
                    if not myglobal.isfloat(v):
                        self.columnVisible(i, False)
            break            
    def allChannel(self):
        # self.db.properties[i]["visible"] = not self.db.properties[i]["visible"]
        for i in range(len(self.db.properties)):
            if self.db.properties[i].get("ele") is None:
                pass
            else:
                self.columnVisible(i, True)
                # self.db.properties[i]["visible"]=True
        self.refresh_grid()
    def noneChannel(self):
        for i in range(len(self.db.properties)):
            if self.db.properties[i].get("ele") is None:
                pass
            else:
                self.columnVisible(i, False)
                # self.db.properties[i]["visible"]=False
        self.refresh_grid()
    def sync(self):
        src_path = r"""\\10.0.114.230\化学分析室\仪器采集\reports\report_import"""
        file_name = os.path.join(src_path, "setting.json")
        print('Reading %s...' % file_name)
        new_setting = json.load(open(file_name, encoding="utf-8"))
        # ffbh_cs
        (left, right) = bjItems.bjitems(
            config_json.setting["ffbh_cs"], new_setting["ffbh_cs"])
        print(left, right)
        for one in right:
            config_json.setting["ffbh_cs"].append(one)
        for one in left:
            new_setting["ffbh_cs"].append(one)
        # ffbh_onh
        (left, right) = bjItems.bjitems(
            config_json.setting["ffbh_onh"], new_setting["ffbh_onh"])
        print(left, right)
        for one in right:
            config_json.setting["ffbh_onh"].append(one)
        for one in left:
            new_setting["ffbh_onh"].append(one)
        # syy
        (left, right) = bjItems.bjitems(
            config_json.setting["syy"], new_setting["syy"])
        print(left, right)
        for one in right:
            config_json.setting["syy"].append(one)
        for one in left:
            new_setting["syy"].append(one)
        # output
        with open(file_name, 'w', encoding="utf-8") as set_file:
            json.dump(new_setting, set_file, indent=4)

    def version(self):
        # from version import version
        # ,QMessageBox.Ok ,QMessageBox.Ok)
        # from PyQt5.QtCore import  QLibraryInfo
        # v=QLibraryInfo.version()
        str1="python:  "+sys.version+"\n"
        # str1+="qt:  "+v.toString()+"\n"
        str1+="app:  "+config_json.setting["version"]+"\n"
        QMessageBox.about(self, '版本号', str1)
    def upgrade_notcheck(self):
        src_path = config_json.setting["src_path"]
        file_name = os.path.join(src_path, "setting.json")
        logging.info('Reading %s...' % file_name)
        file=open(file_name, encoding="utf-8")
        new_setting = json.load(file)
        file.close()
        new_version = int(new_setting["version"])
        version = int(config_json.setting["version"])
        args = ["xcopy.exe", "/Y","/S", os.path.abspath(src_path), getpath.getpath()]
        logging.info(args)
        p=subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True,
        bufsize=1)
        for line in iter(p.stdout.readline, b''):
            logging.info(line.decode("gbk"))
        p.stdout.close()
        p.wait()
        self.close()
    def upgrade(self):
        src_path = config_json.setting["src_path"]
        file_name = os.path.join(src_path, "setting.json")
        logging.info('Reading %s...' % file_name)
        file=open(file_name, encoding="utf-8")
        new_setting = json.load(file)
        file.close()
        new_version = int(new_setting["version"])
        version = int(config_json.setting["version"])
        if new_version > version:
            # logging.info("has new_version", new_version)
            r = QMessageBox.question(
                self, '升级', '是否升级', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if r == QMessageBox.Yes:
                logging.info("yes")
                args = ["xcopy.exe", "/Y","/S", os.path.abspath(src_path), getpath.getpath()]
                logging.info(args)
                p=subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True,
                bufsize=1)
                for line in iter(p.stdout.readline, b''):
                    logging.info(line.decode("gbk"))
                p.stdout.close()
                p.wait()
                self.close()
            else:
                logging.info("no")
        else:

            logging.info("not new_version "+str(new_version))
        pass

    def clearLayout(self, layout):
        while True:
            child = layout.takeAt(0)
            print(child)
            if child == None:
                break
            else:
                print(dir(child))
                child.widget().deleteLater()
    def genchks(self):
        if len(self.chks) < len(self.db.properties):
            # logging.info(list(range(len(self.chks), len(self.fields))))
            for i in range(len(self.chks), len(self.db.properties)):
                c = QCheckBox("")
                self.h.addWidget(c)
                c.pressed.connect(
                    lambda val=i: self.field_click(val)
                )
                self.chks.append(c)

    def resetItems(self):
        # logging.info(self.db.properties)
        self.genchks()
        # logging.info(len(self.chks))
        for i in range(len(self.db.properties)):
            if self.db.properties[i].get("ele") is None:
                self.chks[i].setVisible(False)
            else:
                # logging.info([i,self.db.properties[i]["visible"]])
                self.chks[i].setChecked(self.db.properties[i]["visible"])
                self.chks[i].setText(self.db.properties[i]["header"])
                if self.db.properties[i].get("hide",False)==True:#hidden ele
                    self.chks[i].setVisible(False)
                else:
                    self.chks[i].setVisible(True)
        for i in range(len(self.db.properties), len(self.chks)):
            self.chks[i].setVisible(False)

    def beizhu(self):
        from dlgbeizhu import Dlgbeizhu
        d = Dlgbeizhu()
        r = d.exec()
        if r == 1:
            # self.refresh_ffbh()
            # self.m_comboDelegate=EditDelegateQt(config_json.setting["beizhu"])
            # maybe because m_comboDelegate is already used by talbleview can not change here;error here
            pass
        else:
            pass
    def set_database(self):
        # self.ui.groupBox_images.setVisible(False)
        self.xlswidget=None
        self.ui.groupBox_append.setVisible(False)
        self.ui.widget_middle.setVisible(False)
        self.ui.tableView_report.setVisible(True)
        if config_json.setting["sblx"] in ["ajl_pdf","6300","icap"]: #icp
            from icp import MyDb
            append=config_json.setting["append"].get("icp",{})
            self.db=MyDb(self)

        elif config_json.setting["sblx"] in ["spec","4460","spec_point"]:#spec
            append=config_json.setting["append"].get("spec",{})
            self.db=spectro.MyDb(self)
        elif config_json.setting["sblx"] =="weight":
            append=config_json.setting["append"].get("weight",{})
            self.db=weight.MyDb(self)
        elif config_json.setting["sblx"] =="diding":
            append=config_json.setting["append"].get("diding",{})
            self.db=diding.MyDb(self)            
        elif config_json.setting["sblx"] =="guangdu":
            append=config_json.setting["append"].get("guangdu",{})
            self.db=guangdu.MyDb(self)            
        elif config_json.setting["sblx"]=="zwk":
            append=config_json.setting["append"].get("zwk",{})
            self.db=zwk.MyDb(self)
        elif config_json.setting["sblx"] in ["ajl8900","icap_q","ncs300"]:#icpms
            from icpms import MyDb
            append=config_json.setting["append"].get("icpms",{})
            self.db=MyDb(self)
        elif config_json.setting["sblx"] in ["weight_xls"]:#icpms
            from weight_xls import MyDb
            append={}
            self.db=MyDb(self)            
        else:#csonh
            append=config_json.setting["append"].get("csonh",{})
            self.db=csonh.MyDb(self)
        self.dblViewDele.myformat=self.db.doublefmt
        logging.info([self.db,self.db.inited])
        logging.info(append)
        self.clear_layout(self.h2_append)
        self.clear_layout(self.h3_biaoye)
        self.appends=[]
        if config_json.setting["sblx"]=="6300":
            from cap import ScreenShotWidget
            self.screenShotWg = ScreenShotWidget()
            self.screenShotWg.finished.connect(self.finish_capture)
            self.pushButton_capture=QtWidgets.QPushButton("截图")
            self.pushButton_capture.clicked.connect(self.screenShot)
            self.iv=ImageView()
            sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            self.iv.setSizePolicy(sizePolicy)
            self.iv.setMaximumSize(QtCore.QSize(200, 60))
            self.h2_append.addWidget(self.pushButton_capture)
            self.h2_append.addWidget(self.iv)
        for one in append.keys():
            k=one
            l=append[one][0]
            v=append[one][1]
            w=MyWidget(l,v)
            self.appends.append((k,w))
            self.h2_append.addWidget(w)
            self.ui.groupBox_append.setVisible(True)
        if config_json.setting["sblx"] in ["diding"]:
            from BiaoYe import BiaoYe
            self.biaoye=BiaoYe(self)
            self.h3_biaoye.addWidget(self.biaoye)
        elif config_json.setting["sblx"] in ["weight_xls"]:
            from xlsWidget import XlsWidget
            self.xlswidget=XlsWidget(self)
            # self.ui.widget_middle.setStyleSheet('QWidget { background-color: red }')
            self.h3_biaoye.addWidget(self.xlswidget)
            self.ui.widget_middle.setVisible(True)
            self.ui.pushButton_add.setVisible(False)
            self.ui.pushButton_del.setVisible(False)
            self.ui.pushButton_calc.setVisible(False)
            self.ui.tableView_report.setVisible(False)
        if config_json.setting["sblx"] in ["weight","diding","guangdu"]:
            self.ui.widget_up.setVisible(False)
            self.ui.widget_middle.setVisible(True)
            self.ui.pushButton_add.setVisible(True)
            self.ui.pushButton_del.setVisible(True)
            self.ui.pushButton_calc.setVisible(True)
            if config_json.setting["sblx"]=="guangdu":
                pass 
            elif config_json.setting["sblx"]=="weight":
                pass
            else:
                self.ui.widget_biaoye.setVisible(True)
        elif config_json.setting["sblx"] in ["weight_xls"]:
            self.ui.widget_up.setVisible(False)
        else:
            if config_json.setting["sblx"] in ["zwk"]:
                self.ui.widget_middle.setVisible(True)
                self.ui.widget_biaoye.setVisible(False)
                self.ui.pushButton_calc.setVisible(True)
            self.ui.widget_up.setVisible(True)
            self.ui.pushButton_add.setVisible(False)
            self.ui.pushButton_del.setVisible(False)
        if config_json.setting["sblx"] in ["ncs_cs_db","ncs_onh_db"]:
            self.ui.spinBox_day.setVisible(True)
            self.ui.label_7.setVisible(True)
        else:
            self.ui.spinBox_day.setVisible(False)
            self.ui.label_7.setVisible(False)
        # self.ui.lineEdit_yqbh.setText(config_json.setting["yqbh"])
        self.setWindowTitle("数据上报_"+config_json.setting["sblx"])
        self.resetItems()
        self.init_grid()
    def style_normal(self):   
        a=QtWidgets.qApp
        a.setPalette(QtGui.QPalette());
        a.setStyleSheet(None);  
        config_json.setting["dark"]=-1
    def style_dark(self):
        mystyle.darkStyle(True)
        config_json.setting["dark"]=1
    def style_light(self):
        config_json.setting["dark"]=0
        mystyle.darkStyle(False)
    def ysry_change(self, at):
        config_json.setting["current"]["ysry"] = at

    def syyqm_change(self, at):
        config_json.setting["current"]["syyqm"] = at

    def ffbh_change(self, at):
        config_json.setting["current"]["ffbh"] = at

    def closeEvent(self, event):
        if self.xlswidget!=None:
            self.xlswidget.close()
        config_json.setting["current"]["ffbh"]=self.ui.cmb_ffbh.text()
        config_json.setting["current"]["ff2"]=self.ui.cmb_ff2.text()
        config_json.setting["current"]["js2"]=self.ui.cmb_js2.text()
        config_json.setting["current"]["syy"]=self.ui.cmb_syy.text()
        config_json.setting["current"]["syyqm"]=self.ui.cmb_syyqm.text()
        config_json.setting["current"]["ysry"]=self.ui.cmb_ysry.text()
        config_json.write_setting()
        event.accept()

    # {
    #     if (maybeSave()) {
    #         writeSettings();
    #         event->accept();
    #     } else {
    #         event->ignore();
    #     }
    # }

    # def refresh_syy(self):
    #     ff = config_json.setting["syy"]
    #     self.ui.cmb_syy.clear()
    #     self.ui.cmb_syyqm.clear()
    #     self.ui.cmb_ysry.clear()
    #     for i in ff:
    #         self.ui.cmb_syy.addItem(i)
    #         self.ui.cmb_syyqm.addItem(i)
    #         self.ui.cmb_ysry.addItem(i)
    #     self.ui.cmb_syy.setCurrentIndex(config_json.setting["current"]["syy"])
    #     self.ui.cmb_ysry.setCurrentIndex(
    #         config_json.setting["current"]["ysry"])
    #     self.ui.cmb_syyqm.setCurrentIndex(
    #         config_json.setting["current"]["syyqm"])

    def field_click(self, i):
        logging.info(i)
        self.db.properties[i]["visible"] = not self.db.properties[i]["visible"]
        logging.info(self.db.properties[i]["visible"] )
        if self.db.properties[i]["visible"]:
            # self.chks[i].setChecked(True)
            self.ui.tableView_report.showColumn(i)
            self.ui.tableView.showColumn(i)
        else:
            # self.chks[i].setChecked(False)
            self.ui.tableView_report.hideColumn(i)
            self.ui.tableView.hideColumn(i)
    def init_grid(self):
        try:
            self.objects.sort(reverse=False, key=lambda a:a.num)
            self.objects2.sort(reverse=False, key=lambda a:a.num)
        except TypeError:
            pass 

        self.resetItems()
        self.model.setObjects(self.objects,self.db.properties)
        self.ui.tableView.setModel(self.model)
        
        self.model2.setObjects(self.objects2,self.db.properties)
        self.ui.tableView_report.setModel(self.model2)
        for i, prop in enumerate(self.db.properties):
            # logging.info([i,prop])
            if prop.get('delegate')=="edit":
                self.ui.tableView.setItemDelegateForColumn(i, self.editDelegate)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.editDelegate)
            elif prop.get('delegate')=="floatEdit":
                self.ui.tableView.setItemDelegateForColumn(i, self.floatEdit)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.floatEdit)
            elif prop.get('delegate')=="double":
                self.ui.tableView.setItemDelegateForColumn(i, self.dblViewDele)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.dblViewDele)
            elif prop.get('delegate')=="comboEdit":
                self.ui.tableView.setItemDelegateForColumn(i, self.comboDelegate)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.comboDelegate)
            elif prop.get('delegate')=="date":
                self.ui.tableView.setItemDelegateForColumn(i, self.dateDelegate)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.dateDelegate)
            elif prop.get('delegate')==None:
                self.ui.tableView.setItemDelegateForColumn(i, self.notedit)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.notedit)
        #  self.dblViewDele = DoubleDelegate("%.06f")
        # self.dateDelegate=DateTimeEditDelegateQt()#
        # self.editDelegate=EditDelegateQt()
        # self.floatEdit=FloatEditDelegateQt()
    def refresh_grid(self):
        logging.info("here")
        self.refresh_grid1()
        self.refresh_grid2()

    def refresh_grid1(self):
        try:
            self.objects.sort(reverse=False, key=lambda a:a.num)
        except TypeError:
            print("TypeError")
            pass 
        self.model.setObjectsOnly(self.objects)#,self.db.properties)
        # self.ui.tableView.setModel(self.model)

    def refresh_grid2(self):
        try:
            self.objects2.sort(reverse=False, key=lambda a:a.num)
        except TypeError:
            pass 
        self.model2.setObjectsOnly(self.objects2)#,self.db.properties)
        # self.ui.tableView_report.setModel(self.model2)

    def exit_app(self):
        pass
        # config_json.write_setting()
        self.close()

    def set_ffbh(self):
        from dlgffbh2 import Dlgffbh
        d = Dlgffbh()
        r = d.exec()
        if r == 1:
            self.refresh_ffbh()
        else:
            pass

    def set_syy(self):
        from dlgsyy2 import DlgSyy
        d = DlgSyy()
        r = d.exec()
        if r == 1:
            pass#self.refresh_syy()
        else:
            pass

    def setting(self):
        # from todo import DlgTodo
        # d=DlgTodo()
        # d.exec()
        from dlgsetting import DlgSetting
        calculator = DlgSetting()
        r = calculator.exec()
        # print(r)s
        if r == 1:
            logging.info("setting exit ok")
            # self.ejff=ejff.ejff()
            self.clear()
            if calculator.sblx_changed:
                self.set_database()
        else:
            pass
    def checkBoth(self):
        name = []
        for f in self.db.properties:
            if f["visible"]:
                logging.info(name)
                if (f["ele"]!=None):
                    if(f["ele"][0] in name):
                        QMessageBox.information(self, "", "不能同时选择一个元素的两个通道")
                        return True
                    else:
                        name.append(f["ele"][0])
        return False
    def checkSingle(self):
        n = len(self.objects2)
        r={}
        for row_idx in range(n):
            record = self.objects2[row_idx]
            name=str(record.Sampleid)
            if config_json.setting["pingxing"]==1:
                name=self.remove_pingxing(name)
            if re.match(self.sample_name_pattern,name.strip())!=None:# name.strip()[0:0+2]=="23":
                if r.get(name)!=None:
                    r[name]+=1
                else:
                    r[name]=1
        logging.info(r)
        all=[]
        for k in r.keys():
            if r[k]==1:
                all.append(k)
        if len(all)==0:
            return ""
        else:
            return ",".join(all)
    def lims(self):
        self.db.lims()

    def save_as(self):
        FileDialog = QFileDialog(self)
        FileDirectory = FileDialog.getSaveFileName(self)  # 选择目录，返回选中的路径
        fn = FileDirectory[0]
        if fn != "":
            self.db.output_xlsx(fn)

    def rowcolToStr(self, row, col):
        a = range(65, 70)
        r = {}
        at = 0
        for i in a:
            r[at] = chr(i)
            at += 1
        return r[col]+str(row)

    def clear(self):
        self.objects2 = []
        self.refresh_grid2()
        # self.model2.setQuery("select " + self.fieldStr +
        #                      " from result where 分析时间 in " + self.idstr())
        # self.model2.beizhu = {}

    def unselect(self):
        # print("select")
        # print(self.ids)
        selections = self.ui.tableView_report.selectionModel()
        list1 = selections.selectedIndexes()
        objs = []
        for i in range(len(list1)):
            current = list1[i]
            # if current.column() == 0:
            row = current.row()
            obj= self.model2.getObject(current)
            if obj in objs:
                pass
            else:
                objs.append(obj)
        for obj in objs:
            self.objects2.remove(obj)
            self.objects.append(obj)
        self.refresh_grid()
    def selectall(self):
        # objs=[]
        # for i in range(len(self.objects)):
        #     obj = self.objects[i]
        #     objs.append(obj)
        # for obj in objs:
        #     self.objects.remove(obj)
        self.objects2+=self.objects
        self.objects=[]
        logging.info(len(self.objects))
        logging.info(len(self.objects2))
        self.refresh_grid()
    def select(self):
        # print("select")
        selections = self.ui.tableView.selectionModel()
        list1 = selections.selectedIndexes()
        objs=[]
        for i in range(len(list1)):
            current = list1[i]
            # print(current,dir(current))
            obj = self.model.getObject(current)
            if obj in objs:
                pass
            else:
                objs.append(obj)
        for obj in objs:
            self.objects.remove(obj)
            self.objects2.append(obj)
        self.refresh_grid()
    def day_change(self, v):
        pass
    def query(self):
        print(self.db)
        if self.db==None or  not self.db.inited:
            return
        n=self.ui.spinBox_day.value()
        self.objects=self.db.getDataDays(n)
        # if self.objects and len(self.objects)>0:
        #     logging.info(dir(self.objects[0]))
        self.objects2=[]
        self.init_grid()
        self.firstChannel()
        pass

if __name__ == "__main__":
    import sys
    a = QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    w = MainW()
    w.show()
    sys.exit(a.exec())
        